﻿using System;
using System.Windows;
using GalaSoft.MvvmLight.Messaging;
using MilkCart.ViewModel;
using Microsoft.Phone.Shell;
using System.Windows.Media;
using System.Threading;
using GalaSoft.MvvmLight.Threading;

namespace MilkCart
{
    public partial class MainPage
    {
        internal const string ApiKey = "871d9c0c99ede574fc932915f68f46e1";
        internal const string Secret = "495e6e9a894ea933";

        private readonly ProgressIndicator progIndicator;

        private readonly Timer updateTimer;

        private void UpdateTimerTick(object state = null)
        {
            Messenger.Default.Send(new NotificationMessage(this, NotificationMessages.UpdateMessage));
        }

        private int updatingCount;
        private object updatingLock = new object();

        private void StartedUpdating()
        {
            updatingCount++;
            if (updatingCount < 1)
                updatingCount = 1;
            progIndicator.IsVisible = true;
        }

        private void StoppedUpdating()
        {
            updatingCount--;
            if (updatingCount < 0)
                updatingCount = 0;
            if (updatingCount < 1)
                progIndicator.IsVisible = false;
        }

        private void MessageReceived(NotificationMessage msg)
        {
            switch (msg.Notification)
            {
                case NotificationMessages.StartedUpdating:
                    Dispatcher.BeginInvoke(StartedUpdating);
                    break;
                case NotificationMessages.FinishedUpdating:
                    Dispatcher.BeginInvoke(StoppedUpdating);
                    break;
                case NotificationMessages.SwitchToAccount:
                    MainPivot.SelectedItem = AuthPivotItem;
                    break;
            }
        }

        public MainPage()
        {
            InitializeComponent();

            Messenger.Default.Register<DialogMessage>(this, msg => Dispatcher.BeginInvoke(() => MessageBox.Show(msg.Content, msg.Caption, msg.Button)));
            Messenger.Default.Register<NotificationMessage>(this, MessageReceived);

            SystemTray.SetIsVisible(this, true);

            progIndicator = new ProgressIndicator();
            progIndicator.IsVisible = false;
            progIndicator.IsIndeterminate = true;
            progIndicator.Text = "loading tasks...";

            SystemTray.SetProgressIndicator(this, progIndicator);

            updateTimer = new Timer(UpdateTimerTick);
        }

        private void WindowLoaded(object sender, RoutedEventArgs e)
        {
            DispatcherHelper.Initialize();
            updateTimer.Change(new TimeSpan(0, 0, 0), new TimeSpan(0, 1, 0));
        }
    }
}
